package cn.devpt.dev.auth.service.impl;

import cn.devpt.dev.base.config.WebInterceptor;
import cn.devpt.dev.util.PtUtil;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 用户系统访问记录
 *
 * @author: wangxl
 * @Date: 2018/12/19
 **/
@Aspect
@Configuration
public class UserControllerAop {
    Logger LOG = Logger.getLogger(UserControllerAop.class);

    /*
     * 定义一个切入点
     */
    @Pointcut("execution(* cn.devpt..*.*Controller.*(..))")
    public void excUserRecord() {
    }

    @Around("excUserRecord()")
    public Object arround(ProceedingJoinPoint jp) throws Throwable {
        Long startTime = System.currentTimeMillis();
        String className = jp.getTarget().getClass().getSimpleName();//类名
        String methodName = jp.getSignature().getName();//方法名
        Object rvt = jp.proceed(jp.getArgs());//开始执行业务代码
        Long timeCost = System.currentTimeMillis() - startTime;//花费的时间
        try {//保证记录不影响业务进行,放在业务执行之后,也能保证错误时,不记录
            this.contLog(className, methodName, jp.getArgs(), timeCost);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rvt;
        //
        // return null;
    }

    private void contLog(String clsName, String methodName, Object[] args, Long timeCost) {//控制操作
        if (PtUtil.getCurUser() == null) {
            return;
        }
        String userId = PtUtil.getCurUser().getUserId();
        String menuId = WebInterceptor.hdmenuId.get();//当前菜单id
        new Thread() {//日志式的记录,不应该影响主线程
            @Override
            public void run() {
                String content = "\n用户:" + userId + "\n类:" + clsName + "\n方法:" + methodName + "\n耗时" + timeCost;
                content += "\n菜单id:" + menuId;
                if (args != null && args.length > 0) {
                    //通常业务都是单条增删改,如果有批量增加或者删除的,需要自己写逻辑判断,如某个方法
                    if (args[0] instanceof List) {
                        int num = ((List) args[0]).size();
                        content += ("\n条数:" + num);
                    } else {
                        content += ("\n条数:1");
                    }
                }
                LOG.info(content);
                //执行保存时下面的写法
//                AuthLog syslog = new AuthLog();
//                syslog.setLogId(PtUtil.genUuid());
//                JpaUtil.create(syslog);

            }
        }.start();
    }


}